package com.dnjn.happiness.survey.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.core.web.page.TableDataInfo;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.emo.api.RemoteEmoUserService;
import com.dnjn.happiness.emo.api.model.EmoUserVO;
import com.dnjn.happiness.survey.domain.Question;
import com.dnjn.happiness.survey.domain.SurveyIntervalScore;
import com.dnjn.happiness.survey.domain.SurveyRecord;
import com.dnjn.happiness.survey.domain.vo.AnswerVO;
import com.dnjn.happiness.survey.domain.vo.ExportSurveyRecord;
import com.dnjn.happiness.survey.domain.vo.SurveyRecordVO;
import com.dnjn.happiness.survey.service.IAnswerService;
import com.dnjn.happiness.survey.service.IQuestionService;
import com.dnjn.happiness.survey.service.ISurveyIntervalScoreService;
import com.dnjn.happiness.survey.service.ISurveyRecordService;
import com.dnjn.happiness.system.api.RemoteConfigService;
import com.dnjn.happiness.system.api.RemoteDeptService;
import com.dnjn.happiness.system.api.RemoteRoleService;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysRole;
import com.dnjn.happiness.system.api.domain.SysUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 参加问卷的人记录Controller
 *
 * @author happiness
 * @date 2023-10-23
 */
@Tag(name = "survey record 参加问卷的人记录", description = "参加问卷的人记录")
@RestController
@RequestMapping("/record")
public class SurveyRecordController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SurveyRecordController.class);
    @Autowired
    private ISurveyRecordService surveyRecordService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private ISurveyIntervalScoreService surveyIntervalScoreService;
    @Autowired
    private IAnswerService answerService;
    @Autowired
    private RemoteDeptService deptService;
    @Autowired
    private RemoteUserService userService;
    @Autowired
    private RemoteRoleService roleService;
    @Autowired
    private RemoteConfigService configService;
    @Autowired
    private RemoteEmoUserService emoUserService;

    //去评价-后台
    @Log(title = "参加问卷的人记录", businessType = BusinessType.INSERT)
    @PostMapping("/goToSurveyRecordAnswerAppraise1")
    @RequiresPermissions("survey:record:edit")
    @Operation(summary = "去评价", description = "appraiser评价人,answerAppraise评价,surveyRecordId,etypeId不能为空")
    public AjaxResult goToPing1(@RequestBody SurveyRecord surveyRecord) {
        Assert.notNull(surveyRecord.getAppraiser(), "评价人不能为空");
        Assert.notNull(surveyRecord.getAnswerAppraise(), "答题评价不能为空");
        surveyRecord.setCreateBy(SecurityUtils.getUsername());
        return toAjax(surveyRecordService.goToPing(surveyRecord));
    }

    //去评价-小程序
    @Log(title = "参加问卷的人记录", businessType = BusinessType.INSERT)
    @PostMapping("/goToSurveyRecordAnswerAppraise")
    @Operation(summary = "去评价", description = "appraiser评价人,answerAppraise评价,surveyRecordId,etypeId不能为空")
    public AjaxResult goToPing(@RequestBody SurveyRecord surveyRecord) {
        Assert.notNull(surveyRecord.getAppraiser(), "评价人不能为空");
        Assert.notNull(surveyRecord.getAnswerAppraise(), "答题评价不能为空");
        surveyRecord.setCreateBy(SecurityUtils.getUsername());
        return toAjax(surveyRecordService.goToPing(surveyRecord));
    }

    /**
     * 后台查询当前登陆人的问卷记录列表
     */
    @PostMapping("/list1")
    @RequiresPermissions("survey:record:list")
    public TableDataInfo list1(@RequestBody SurveyRecordVO surveyRecordVO) {
        startPage();
        List<SurveyRecordVO> list = surveyRecordService.getPage1(surveyRecordVO);
        return getDataTable(list);

    }

    /**
     * wx查询当前登陆人的问卷记录列表
     */
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody SurveyRecordVO surveyRecordVO) {
        startPage();
        List<SurveyRecordVO> list = surveyRecordService.getPage1(surveyRecordVO);
        return getDataTable(list);

    }

    //点击切换 进入详情试图 -小程序
    @Operation(summary = "点击切换 进入详情视图")
    @GetMapping("/goToTheDetailsView")
    public AjaxResult goToTheDetailsView(@RequestParam Long surveyId) {
        List<SysUser> userList = surveyRecordService.goToTheDetailsView(surveyId);
        return success(userList);
    }

    //点击主管查看里边详情-小程序
    @Operation(summary = "查看各个主管下边的人员分数详情")
    @GetMapping("/ForSurveyDetailsSeeFeedbackBySurveyIdAndLeaderId")
    public AjaxResult forSurveyDetailsSeeFeedbackBySurveyIdAndLeaderId(@RequestParam Long surveyId, @RequestParam Long leaderId) {


        List<SurveyRecord> surveyRecords = surveyRecordService.forSurveyDetailsSeeFeedbackBySurveyIdAndLeaderId(surveyId, leaderId);

        int total = surveyRecords.size();

        ArrayList<SurveyRecord> listY = new ArrayList<>();
        ArrayList<SurveyRecord> listN = new ArrayList<>();

        surveyRecords.stream().forEach(surveyRecord -> {
            String recordStatus = surveyRecord.getRecordStatus();
            if (recordStatus.equals("Y")) {
                listY.add(surveyRecord);
            } else {
                listN.add(surveyRecord);
            }
        });

        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("total", total);
        ajaxResult.put("notInvolved", listN);
        ajaxResult.put("participated", listY);
        return AjaxResult.success(ajaxResult);

    }

    //  小程序- 筛选问卷 Screening questionnaires
    @Operation(summary = "点击筛选-筛选问卷")
    @GetMapping("/screeningQuestionnaires")
    public AjaxResult screeningQuestionnaires(@RequestParam Long surveyId) {
        List<Question> questionList = questionService.querySurveyBySurveyIdX(surveyId);
        //返回 该问卷的分值区间
        List<SurveyIntervalScore> surveyIntervalScoreList = surveyIntervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyId).list();
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("score", surveyIntervalScoreList);
        ajaxResult.put("questionList", questionList);
        return success(ajaxResult);


    }

    @RequiresPermissions("survey:record:query")
    @Operation(summary = "点击筛选-筛选问卷-后台")
    @GetMapping("/screeningQuestionnairesAdmin")
    public AjaxResult screeningQuestionnairesAdmin(@RequestParam Long surveyId) {
        List<Question> questionList = questionService.querySurveyBySurveyIdX(surveyId);
        //返回 该问卷的分值区间
        List<SurveyIntervalScore> surveyIntervalScoreList = surveyIntervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyId).list();
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("score", surveyIntervalScoreList);
        ajaxResult.put("questionList", questionList);
        return success(ajaxResult);

    }


    /**
     * 获取部门列表 通用方法- 小程序
     */

    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = new ArrayList<>();
        R<List<SysDept>> result = deptService.selectDeptList(dept, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            depts = result.getData();
        }
        return success(depts);
    }


    //  提交筛选条件 -小程序
    @Operation(summary = "点击筛选-提交筛选")
    @PostMapping("/screeningSubmit")
    public AjaxResult screeningSubmit(@RequestBody AnswerVO answerVO) {
        return success(surveyRecordService.screeningSubmit(answerVO));
    }

    @RequiresPermissions("survey:record:query")
    @Operation(summary = "点击筛选-提交筛选-后台")
    @PostMapping("/screeningSubmitAdmin")
    public AjaxResult screeningSubmitAdmin(@RequestBody AnswerVO answerVO) {
        return success(surveyRecordService.screeningSubmit(answerVO));
    }


    //  新增 小程序  智能筛选功能  1.判断快乐值低的人  或者  问卷分数 是差的人数  (可能还需要统计一下数量)
    // 智能筛选
    @Operation(summary = "小程序-问卷智能筛选")
    @GetMapping("/IntelligentScreening")
    public AjaxResult intelligentScreening(@RequestParam Long surveyId) {
        List<SurveyRecord> list = new ArrayList<>();
        // 快乐值低于监控数值的 或者 问卷结果等级是 差(1) 的 被筛选出来
        List<SurveyRecord> surveyRecords = surveyRecordService.queryRecordX(surveyId);
        ArrayList<SurveyRecord> lower = new ArrayList<>();//装分数低的 record
        int num = 0;
        R<String> result = configService.getThresholdDateaApi(SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            num = Integer.parseInt(result.getData());
        }

        for (SurveyRecord SurveyRecord : surveyRecords) {
            EmoUserVO emoUser = null;
            R<EmoUserVO> resultEmoUser = emoUserService.getInfoByUserId(SurveyRecord.getUserId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultEmoUser) && StringUtils.isNotNull(resultEmoUser.getData())) {
                emoUser = resultEmoUser.getData();
            }
            if (null != emoUser) {
                if (null != emoUser.getHappinessScore()) {
                    Integer happinessScore = emoUser.getHappinessScore().intValue();
                    if (happinessScore < num) {
                        lower.add(SurveyRecord);
                    }
                }
            }
        }

        lower.stream().forEach(surveyRecord -> {
            getRoleAndDept(surveyRecord);
            list.add(surveyRecord);

        });


        //  这里 得 加上那个问卷结果等级是差的  那个条件
        List<SurveyRecord> gradeLower = surveyRecordService.selectGradeX(surveyId);

        gradeLower.stream().forEach(surveyRecord -> {
            getRoleAndDept(surveyRecord);
            list.add(surveyRecord);

        });
//        AjaxResult ajax = new AjaxResult();
//
//        ajax.put("surveyHappinessScoreLower", lower);
//        ajax.put("userListgRrade", gradeLower);
//        return ajax;
        return success(list);

    }


    // 小程序-点击切换进入视图详情  不是二层结构的(2023.11.30更改)
//    @Operation(summary = "点击切换 进入详情视图-不是二层结构的(2023.11.30更改)")
//    @GetMapping("/goToTheSurveyDetailsView")
//    public AjaxResult goToTheSurveyDetailsView(@RequestParam Long surveyId) {
//
//        List<SurveyRecord> userList = surveyRecordService.goToTheSurveyDetailsView(surveyId);
//
//        userList.stream().forEach(surveyRecord -> {
//            Long deptId = surveyRecord.getDeptId();
//            if(null != deptId){
//                SysDept sysDept = deptService.selectDeptById(deptId);
//                surveyRecord.setSysDept(sysDept);
//            }
//        });
//
//        ArrayList<SurveyRecord> listY = new ArrayList<>();
//        ArrayList<SurveyRecord> listN = new ArrayList<>();
//
//        userList.stream().forEach(surveyRecord -> {
//            String recordStatus = surveyRecord.getRecordStatus();
//            if (recordStatus.equals("Y")) {
//                listY.add(surveyRecord);
//            } else {
//                listN.add(surveyRecord);
//            }
//        });
//        AjaxResult ajaxResult = new AjaxResult();
//
//        ajaxResult.put("notInvolved", listN);
//        ajaxResult.put("participated", listY);
//        return AjaxResult.success(ajaxResult);
//    }

    @Operation(summary = "点击切换 进入详情视图-不是二层结构的(2023.11.30更改)-已参与-带分页", description = "role:2高亮;1:普通,默认1普通")
    @GetMapping("/goToTheSurveyDetailsView")
    public AjaxResult goToTheSurveyDetailsView(@RequestParam Long surveyId, @RequestParam String SurveyStatus, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<SurveyRecord> page = Page.of(current, size);

        Page<SurveyRecord> userList = surveyRecordService.goToTheSurveyDetailsView(page, surveyId, SurveyStatus);
        List<SurveyRecord> records = userList.getRecords();


        records.stream().forEach(surveyRecord -> {
            getRoleAndDept(surveyRecord);
        });


        return AjaxResult.success(userList);
    }

    //    @Operation(summary = "导出")
//    @PostMapping("/export")
//    public void goToTheSurveyDetailsViewExport(HttpServletResponse response, Long surveyId) {
//        List<SurveyRecord> userList = surveyRecordService.exportSurveyId(surveyId);
//        List<SurveyRecordVO> userListVO=new ArrayList<SurveyRecordVO>();
//
//        userList.stream().forEach(surveyRecord -> {
//            SurveyRecordVO surveyRecordVO = new SurveyRecordVO();
//            Long deptId = surveyRecord.getDeptId();
//            if (null != deptId) {
//                SysDept sysDept = deptService.selectDeptById(deptId);
//                surveyRecord.setSysDept(sysDept);
//                String parentName = sysDept.getParentName();
//                String deptName = sysDept.getDeptName();
//                surveyRecord.setParentNameAndDeptName(parentName+"-"+deptName);
//            }
//            BeanUtils.copyPropsIgnoreNull(surveyRecord, surveyRecordVO);
//            userListVO.add(surveyRecordVO);
//        });
//
//        ExcelUtil<SurveyRecordVO> util = new ExcelUtil<SurveyRecordVO>(SurveyRecordVO.class);
//        util.exportExcel(response, userListVO, "问卷数据");
//
//    }
    @Log(title = "问卷导出", businessType = BusinessType.EXPORT)
    @Operation(summary = "导出")
    @PostMapping("/export")
    public void goToTheSurveyDetailsViewExport(HttpServletResponse response, Long surveyId) {
        List<ExportSurveyRecord> userList = surveyRecordService.exportSurveyRecord(surveyId);
        userList.stream().forEach(ExportSurveyRecord -> {
            String recordStatus = ExportSurveyRecord.getRecordStatus();
            if (null != recordStatus && recordStatus.equals("Y")) {
                ExportSurveyRecord.setRecordStatus("是");
                ExportSurveyRecord.setSurveyRecordDate(ExportSurveyRecord.getUpdateTime());
                List<SurveyIntervalScore> list = surveyIntervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, ExportSurveyRecord.getSurveyId()).eq(SurveyIntervalScore::getDeleted, '0').list();
                for (SurveyIntervalScore surveyIntervalScore : list) {
                    if (null != ExportSurveyRecord.getSurveyScore() && ExportSurveyRecord.getSurveyScore() >= surveyIntervalScore.getStartScore() && ExportSurveyRecord.getSurveyScore() <= surveyIntervalScore.getEndScore()) {
                        ExportSurveyRecord.setResult(surveyIntervalScore.getResult());
                    }
                }
            } else {
                ExportSurveyRecord.setSurveyRecordDate(null);
                ExportSurveyRecord.setSurveyScore(0);
                ExportSurveyRecord.setResult(null);
                ExportSurveyRecord.setRecordStatus("否");
            }

            Long deptId = ExportSurveyRecord.getDeptId();
            if (null != deptId) {
                SysDept sysDept = new SysDept();
                R<SysDept> result = deptService.getInfoById(deptId, SecurityConstants.INNER);
                if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                    sysDept = result.getData();
                }
                String parentName = sysDept.getParentName();
                String deptName = sysDept.getDeptName();
                ExportSurveyRecord.setParentNameAndDeptName(parentName + "-" + deptName);
            }


        });

        ExcelUtil<ExportSurveyRecord> util = new ExcelUtil<ExportSurveyRecord>(ExportSurveyRecord.class);
        util.exportExcel(response, userList, "问卷数据");

    }
//  答题详情  对应分值区间筛选

    @Operation(summary = "答题详情  对应分值区间筛选-带分页-echarts图页面上的筛选")
    @GetMapping("/answerDetailsFilterTheCorrespondingScoreRange")
    public AjaxResult answerDetailsFilterTheCorrespondingScoreRange(@RequestParam Long surveyId, @RequestParam Integer startScore, @RequestParam Integer endScore, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<SurveyRecord> page = Page.of(current, size);

        Page<SurveyRecord> userList = surveyRecordService.answerDetailsFilterTheCorrespondingScoreRange(page, surveyId, startScore, endScore);
        List<SurveyRecord> records = userList.getRecords();


        records.stream().forEach(surveyRecord -> {
            getRoleAndDept(surveyRecord);
        });


        return AjaxResult.success(userList);
    }


//    List<Question> questionList = answerVO.getQuestionList();
//    ArrayList<SurveyUserVO> objects = new ArrayList<>();
//        if (null != answerVO.getStartScore() || null != answerVO.getEndScore()) {
//        surveyUserVOList.stream().forEach(surveyUserVO -> {
//
//            Long surveyId = surveyUserVO.getSurveyId();
//            List<SurveyIntervalScore> intervalScores = surveyIntervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyId).list();
//            // 判断分区间
////                for (SurveyIntervalScore intervalScore:intervalScores){
////                    if (null != answerVO.getStartScore() && answerVO.getStartScore() >= intervalScore.getStartScore() &&
////                            null != answerVO.getEndScore() && answerVO.getEndScore() <= intervalScore.getEndScore()) {//两边边界值都有
////                        objects.add(surveyUserVO);
////                        continue;
////                    }
////                    if (null == answerVO.getStartScore() && null != answerVO.getEndScore() && answerVO.getEndScore() < intervalScore.getEndScore()) {//
////                        objects.add(surveyUserVO);
////                    }
////                    if (null != answerVO.getStartScore() && null == answerVO.getEndScore() && answerVO.getStartScore() > intervalScore.getStartScore()) {//
////                        objects.add(surveyUserVO);
////                    }
////                }
//        });
//    }

    private void getRoleAndDept(SurveyRecord surveyRecord) {
        Long userId = surveyRecord.getUserId();
        // 判断角色
        if (null != userId) {
            List<SysRole> sysRoles = new ArrayList<>();
            R<List<SysRole>> result = roleService.queryRole(userId, SecurityConstants.INNER);
            if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                sysRoles = result.getData();
            }
            sysRoles.stream().forEach(sysRole -> {
                if (null != sysRole.getRoleKey() && sysRole.getRoleKey().contains("common")) {
                    surveyRecord.setRole("1");//普通
                }
                if (null != sysRole.getRoleKey() && !sysRole.getRoleKey().contains("common")) {
                    surveyRecord.setRole("2");//高亮
                }
            });
        }
        Long deptId = surveyRecord.getDeptId();
        if (null != deptId) {
            SysDept sysDept = new SysDept();
            R<SysDept> result = deptService.getInfoById(deptId, SecurityConstants.INNER);
            if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                sysDept = result.getData();
            }
            surveyRecord.setSysDept(sysDept);
        }
    }


}
